﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Mime
{
    using System;
    using System.Globalization;
    using System.IO;

    /// <summary>Represents a header field that contains a date(see <a href="http://www.ietf.org/rfc/rfc5322.txt">RFC
    /// 5322</a> 3.3.).</summary>
    /// <threadsafety static="true" instance="false"/>
    public sealed class DateHeaderField : HeaderField<DateHeaderField>
    {
        private const string CommonFormat = "ddd, dd MMM yyyy HH:mm:ss";
        private const string NormalDateFormat = CommonFormat + " zzz";
        private static readonly DateTime defaultDate = new DateTime(0, DateTimeKind.Utc);
        private static readonly string mimeDefaultDate =
            defaultDate.ToString(CommonFormat, CultureInfo.InvariantCulture) + " +0000";

        private DateTime dateUtc = defaultDate;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Initializes a new instance of the <see cref="DateHeaderField"/> class.</summary>
        /// <param name="name">The name of the header field, usually <see cref="HeaderFieldNames.Date"/>.</param>
        /// <exception cref="ArgumentException"><paramref name="name"/> is <c>null</c> or empty.</exception>
        public DateHeaderField(string name) : base(name)
        {
        }

        /// <summary>Gets or sets the date in UTC.</summary>
        /// <remarks>The default value is <see cref="DateTime.MinValue"/> with <see cref="DateTime.Kind"/> =
        /// <see cref="DateTimeKind.Utc"/>, which is set during construction and when the parser does not find a valid
        /// date.</remarks>
        public DateTime DateUtc
        {
            get { return this.dateUtc; }
            set { this.dateUtc = value; }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal sealed override void WriteTo(Stream stream)
        {
            var mimeDate = this.dateUtc == defaultDate ? mimeDefaultDate : this.dateUtc.ToLocalTime().ToString(
                NormalDateFormat, CultureInfo.InvariantCulture).Remove(29, 1);
            HeaderFieldHelper.FoldHeaderField(this.Name, new[] { new HeaderFieldBodyPart(mimeDate, false) }, stream);
        }
    }
}
